package org.bean.box.tcp;

import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

@Slf4j
public class TcpDecoder extends CumulativeProtocolDecoder {

    @Override
    protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
        log.info("doDecode");
        int position = in.position();
        int totalLength = in.remaining();
        if(totalLength > 0) {
            log.info("id : " + session.getId() + " position : " + position + " totalLength : " + totalLength);
            out.write(getIoBuffer(in, totalLength));
            in.position(position + totalLength);
            return true;
        }
        return false;
    }

    /**
     *
     * @param ioBuffer
     * @param length
     * @return
     */
    public byte[] getIoBuffer(IoBuffer ioBuffer, int length) {
        byte[] array = new byte[length];
        ioBuffer.get(array);
        return array;
    }
}
